package com.nettyBasic.n5_handlerAndPipeline;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author： pang-yun
 * @date： 2021-09-13 13:48
 * 功能目的 ：用于  pipeline  流水线  加上 各种handler（工序）
 *
 * ChannelOutBoundHandlerAdapter 只有 在客户端 向外写东西时 才会触发
 * 而且 channelOutBoundHandlerAdapter 几个处理器的输出顺序是和 channelInboundHandlerAdapter 的输出顺序是相反的
 */
@Slf4j
public class PipelineServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup(2);

        ChannelFuture channelFuture = new ServerBootstrap()
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 1. 通过 channel 拿到 pipeline
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        // 2. 添加处理器 head -> c1 -> c2 -> c3 -> tail
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast("c1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info("1");
                               // ByteBuf buf = (ByteBuf) msg;
                                System.out.println(msg);
                                //String string = buf.toString(Charset.defaultCharset());
                                super.channelRead(ctx, msg);
                            }
                        });
                        pipeline.addLast("c2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info("2");
                                Student student = new Student((String) msg);
                                System.out.println(student);
                                super.channelRead(ctx, student);
                            }
                        });
                        pipeline.addLast("c3", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info("3");

                                super.channelRead(ctx, msg);
                                // ctx.alloc().buffer() 分配空间 给出一个 buffer
                                nioSocketChannel.writeAndFlush(ctx.alloc().buffer().writeBytes("Hello,this is Server..".getBytes()));
                            }
                        });

                        // ---ChannelOutBoundHandlerAdapter 只有 在客户端 向外写东西时 才会触发
                        pipeline.addLast("o1", new ChannelOutboundHandlerAdapter() {
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.info("out-1");
                                super.write(ctx, msg, promise);
                            }
                        });
                        pipeline.addLast("o2", new ChannelOutboundHandlerAdapter() {
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.info("out-2");
                                super.write(ctx, msg, promise);
                            }
                        });
                        pipeline.addLast("o3", new ChannelOutboundHandlerAdapter() {
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.info("out-3");
                                super.write(ctx, msg, promise);
                            }
                        });
                    }
                }).bind(9999);

        Channel channel = channelFuture.sync().channel();
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                bossGroup.shutdownGracefully();
                workGroup.shutdownGracefully();
            }
        });
    }


    @Data
    @AllArgsConstructor
    static class Student{
        private String name;
    }
}
